package com.example.alibabanacosdiscoveryclient01.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeAudioTranscriptionOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import com.alibaba.cloud.ai.dashscope.audio.transcription.AudioTranscriptionModel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.UrlResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author:guoq
 * @date:2024/6/27
 * @descripion:
 */
@RestController
@RequestMapping("/ai")
@Tag(name = "audioAI应用")
public class AudioAiController {
    @Autowired
    private SpeechSynthesisModel speechSynthesisModel;
    @Autowired
    private AudioTranscriptionModel transcriptionModel;

    @GetMapping("/tts")
    @Operation(summary = "文字转语音")
    public String audio(String input,String path) throws IOException {
        SpeechSynthesisResponse call = speechSynthesisModel.call(new SpeechSynthesisPrompt(input));
        File file=new File(path+"/output.mp3");
        if (!file.exists()) {
            //先得到文件的上级目录，并创建上级目录，在创建文件
            file.getParentFile().mkdir();
            //创建文件
            file.createNewFile();
        }
        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuffer byteBuffer = call.getResult().getOutput().getAudio();
            fos.write(byteBuffer.array());
            return  "file is in "+path+"/output.mp3";
        }
        catch (IOException e) {
            throw new IOException(e.getMessage());
        }
    }
    @GetMapping("/stt")
    @Operation(summary = "语音转文字")
    public String audio(String path) throws IOException {
        AudioTranscriptionResponse response = transcriptionModel.call(
                new AudioTranscriptionPrompt(
                        new UrlResource(path),
                        DashScopeAudioTranscriptionOptions.builder()
                                .withModel("sensevoice-v1")
                                .build()
                )
        );

        return response.getResult().getOutput();
    }
}
